import 'package:star_author/provider/user.dart';
import 'package:star_author/utils/common_util/toast/custom_toast.dart';
import 'package:star_author/utils/http/api_manager.dart';
import 'package:star_author/utils/http/http_util.dart';
import 'package:star_author/utils/media_recorder_util.dart';
import 'package:star_author/utils/rouces_util.dart';
import 'package:star_author/utils/toast_util.dart';
import 'package:star_author/utils/user_util.dart';
import 'package:star_author/utils/utils.dart';
import 'package:star_author/views/stream/local_video_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:package_info/package_info.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';

import '../stream/open_live.dart';

class Index extends StatefulWidget {
  Index({Key? key}) : super(key: key);

  @override
  State<Index> createState() => _IndexState();
}

class _IndexState extends State<Index> {
  List wraps = [
    {
      "title": "本地视频管理",
      "icon": "ic_index_local_videos",
    },
    {
      "title": "上传日志",
      "icon": "ic_index_upload_log",
    },
    {
      "title": "关闭直播间",
      "icon": "ic_index_close_live_lt",
    },
  ];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initVersion();
  }

  initVersion() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    //版本名
    version = packageInfo.version;
    if (mounted) setState(() {});
  }

  String version = "";

  @override
  Widget build(BuildContext context) {
    bool is_login = UserUtil.isLogin(context);
    UserProvider provider = Provider.of<UserProvider>(context, listen: false);
    int id = 0;
    String cover = "";
    String name = "首页";
    bool isAnchor = false;
    String anchor_changed_at = "";
    if (provider.user!['id'] != 0) {
      //登录
      List maintain_studios = provider.user!['maintain_studios'] ?? [];
      if (maintain_studios.length > 0) {
        id = maintain_studios[0]['id'] ?? 0;
        cover = maintain_studios[0]['vertical_cover'] ?? "";
        name = maintain_studios[0]['name'] ?? "";
        anchor_changed_at = maintain_studios[0]['anchor_changed_at'] ?? "";
        isAnchor = true;
      }
    }
    //主播信息
    Map? anchor = provider.user?['anchor'] ?? {};
    bool isAnchorAccount = false;
    if (anchor?.isNotEmpty ?? false) {
      isAnchorAccount = true;
    }
    return Container(
        color: rgba(245, 245, 245, 1),
        padding: EdgeInsets.symmetric(
          vertical: 12.w,
          horizontal: 12.w,
        ),
        height: Get.height,
        child: Stack(
          children: [
            isAnchor
                ? Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '主播: ${anchor?['nickname'] ?? ""}',
                        style: TextStyle(
                          fontSize: 24.sp,
                          color: rgba(51, 51, 51, 1),
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      SizedBox(
                        height: 6.w,
                      ),
                      Text(
                        '上次直播时间: ${formatDate(anchor_changed_at)}',
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: rgba(153, 153, 153, 1),
                        ),
                      ),
                      SizedBox(
                        height: 20.w,
                      ),
                      GestureDetector(
                        child: Container(
                          height: 84.w,
                          width: Get.width,
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(4.w),
                            image: DecorationImage(
                              image: AssetImage(
                                RoucesUtil.getAssets('bg_index_to_open_live'),
                              ),
                            ),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                children: [
                                  SizedBox(
                                    width: 20.w,
                                  ),
                                  RoucesUtil.getAssetsIcon(
                                      'ic_index_to_open_live_lt', 60),
                                  SizedBox(
                                    width: 13.w,
                                  ),
                                  Text(
                                    '去直播',
                                    style: TextStyle(
                                      fontSize: 16.sp,
                                      color: rgba(51, 51, 51, 1),
                                      fontWeight: FontWeight.w500,
                                    ),
                                  ),
                                ],
                              ),
                              Container(
                                child: RoucesUtil.getAssetsIcon(
                                    'ic_index_to_open_live_jump_lt', 20.w),
                                margin: EdgeInsets.only(
                                  right: 20.w,
                                ),
                              ),
                            ],
                          ),
                        ),
                        onTap: () {
                          toOpenLive();
                        },
                      ),
                      SizedBox(
                        height: 10.w,
                      ),
                      Container(
                        width: Get.width,
                        padding: EdgeInsets.only(
                          top: 12.w,
                          bottom: 20.w,
                        ),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(6.w),
                        ),
                        child: Wrap(
                          children: List.generate(
                            wraps.length,
                            (index) => GestureDetector(
                              child: Container(
                                width: (Get.width - 24.w) / 3.1,
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    RoucesUtil.getAssetsIcon(
                                        wraps[index]['icon'], 60.w),
                                    SizedBox(
                                      height: 4.w,
                                    ),
                                    Text(
                                      wraps[index]['title'],
                                      style: TextStyle(
                                        fontSize: 12.sp,
                                        color: rgba(51, 51, 51, 1),
                                        fontWeight: FontWeight.w500,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              onTap: () {
                                onClick(index, id);
                              },
                            ),
                          ),
                        ),
                      ),
                    ],
                  )
                : Container(),
            Positioned(
              child: Container(
                width: Get.width - 24.w,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      'V$version',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        color: Color(0xFF969798),
                        fontSize: 20.sp,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ],
                ),
              ),
              bottom: 35,
            ),
          ],
        ));
  }

  toOpenLive() {
    //判断是否登录
    HttpUtil.commonRequest(
      Get.context!,
      ApiManager.current_tiny,
      isLoading: false,
      isErrorToast: false,
    ).then((value) async {
      Provider.of<UserProvider>(context, listen: false)
          .set(key: 'userInfo', value: value.data);
      Map<Permission, PermissionStatus> map = await _initPermission();
      if (map[Permission.camera] == PermissionStatus.granted &&
          map[Permission.microphone] == PermissionStatus.granted &&
          map[Permission.storage] == PermissionStatus.granted) {
        List maintain_studios = value.data?['maintain_studios'] ?? [];
        if (maintain_studios.length > 0) {
          bool _switch = maintain_studios[0]['switch'] ?? false;
          bool visible = maintain_studios[0]['visible'] ?? false;
          if (_switch) {
            ToastUtil.show("当前直播间有人在播，请稍后再试");
            return;
          }
          if (!visible) {
            ToastUtil.show("当前直播间已被撤销，不能开播!");
            return;
          }
          Get.to(OpenLive());
        } else {
          ToastUtil.show("当前用户没有直播间");
        }
      } else if (map[Permission.camera] == PermissionStatus.permanentlyDenied) {
        CustomToast.show("摄像头权限被永久拒绝，请在设置中通过");
        openAppSettings();
      } else if (map[Permission.microphone] ==
          PermissionStatus.permanentlyDenied) {
        CustomToast.show("麦克风权限被永久拒绝，请在设置中通过");
        openAppSettings();
      } else if (map[Permission.storage] ==
          PermissionStatus.permanentlyDenied) {
        CustomToast.show("文件读写权限被永久拒绝，请在设置中通过");
        openAppSettings();
      } else {
        _initPermission();
      }
    });
  }

  Future _initPermission() {
    return [Permission.camera, Permission.microphone, Permission.storage]
        .request();
  }

  onClick(index, id) {
    switch (index) {
      case 0:
        Get.to(LocalVideoPage());
        break;
      case 1:
        MediaRecorderUtil.uploadLogLogFile();
        break;
      case 2:
        //判断是否登录
        HttpUtil.commonRequest(
          context,
          '/api/v1/studios/${id}/close',
          method: HttpUtil.MethodPost,
        ).then((value) {
          CustomToast.show("关闭直播间成功");
        });
        break;
    }
  }
}
